<?php

namespace SinoPHP\BbdBoss\Controller;

use SinoPHP\BbdBoss\AdminController;
use Upfor\UpforPHP\Library\Password;
use SinoPHP\BbdBoss\Library\AdminAuth;

/**
 * 管理员账户管理
 */
class AdminUser extends AdminController {

    /**
     * 登录页面
     */
    public function login() {
        if (isAdminLogin()) {
            redirect('/');
        }

        $this->view([], true);
    }

    /**
     * 登录验证
     */
    public function verifyLogin() {
        $msg = '账号或密码错误';
        if (!request()->isPost()) {
            $this->error(101007, $msg);
        }

        $email = request()->post('email');
        $password = request()->post('password');

        // 账号不可为空
        if (empty($email)) {
            $this->error(101004, $msg);
        }

        // 支持不输入邮箱后缀进行登录
        if (strpos($email, '@') === false) {
            $email = $email . '@sinobbd.com';
        }

        // 校验账号是否为邮箱
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->error(101005, $msg);
        }

        // 登录失败次数限制(仅以COOKIE作为标识)
        // 5分钟内仅可错误5次
        $loginFailedInfo = session('loginFailedTimes');

        if ($loginFailedInfo['fail_times'] >= 5 && $loginFailedInfo['start_time'] - time() <= 300) {
            $this->error(101006, '登录失败次数太多, 请稍后重试');
        }

        // 根据email查询账号是否存在
        $userInfo = model('AdminUser')->getRow('*', ['email' => $email]);
        if (!$userInfo) {
            $this->error(101001, $msg);
        }

        // 用户ID
        $userId = $userInfo['admin_user_id'];

        // 判断账号是否被禁用
        if (!$userInfo['status']) {
            $this->error(101003, '账号已封停, 请联系管理员');
        }

        // 验证密码
        if (Password::validate($password, $userInfo['password'])) {  
            // 获取用户菜单&权限
            // $auth = new AdminAuth();
            // $menus = $auth->getMenusByUser($userId);
            // $nodes = $auth->getNodesByUser($userId);
            $menus = 1;
            $nodes = 2;

            // 判断是否为超级管理员
            // $isSuper = $auth->isSuper($userId);
            $isSuper = 1;

            // 更新登录成功后的信息
            $updateData = [
                'last_login_ip' => request()->getRemoteIp(),
                'last_login_time' => time(),
            ];
            model('AdminUser')->update($updateData, ['admin_user_id' => $userInfo['admin_user_id']]);

            // 记录用户登录信息到SESSION
            $userLoginInfo = [
                'admin_user_id' => $userInfo['admin_user_id'],
                'email' => $userInfo['email'],
                'real_name' => $userInfo['real_name'],
                'ip' => request()->getRemoteIp(),
                'loginTime' => time(),
                'isSuper' => $isSuper,
                'nodes' => $nodes,
                'menus' => $menus,
            ];

            session(getAdminUserLoginToken(), $userLoginInfo);

            // 清除登录失败的计数
            session('loginFailedTimes', null); // 删除登录相关信息

            // 记录登录成功日志
            $this->addActionLog($email . '登录成功', $userLoginInfo);
            if (!request()->isPost()) {
                $defaultRoute = config('route', 'config');
                //$next = "/{$defaultRoute['defaultController']}/$defaultRoute['defaultController']";
                // redirect($next);
            }
            $this->success([], '登录成功');
        } else {
            // 登录失败次数计数(仅以COOKIE作为标识)
            $loginFailedTimes = session('loginFailedTimes');
            if (empty($loginFailedTimes)) {
                $loginFailedTimes['fail_times'] = 0;
                $loginFailedTimes['start_time'] = time();
            }
            $loginFailedTimes['fail_times'] += 1;

            session('loginFailedTimes', $loginFailedTimes);

            // 记录登录失败日志
            $this->addActionLog($email . '登录失败');

            $this->error(101002, $msg);
        }
    }

    /**
     * 退出登录
     */
    public function logout() {
        $loginToken = getAdminUserLoginToken();

        // 记录退出登录日志
        $userLoginInfo = session($loginToken); // 从SESSION获取用户登录信息
        $userLoginInfo && $this->addActionLog($userLoginInfo['email'] . '退出登录');
        session($loginToken, null); // 删除登录相关信息

        if (request()->isPost()) {
            $this->success([], '退出成功');
        } else {
            redirect('/AdminUser/login');
        }
    }

}
